package com.ming.springboot.security;

import com.ming.springboot.mbg.mapper.UserMapper;
import com.ming.springboot.mbg.model.User;
import com.ming.springboot.mbg.model.UserExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by mqsi on 2022/5/24 14:57
 */
@Component
public class SelfUserDetailService implements UserDetailsService {
	@Autowired
	UserMapper userMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		UserExample userExample = new UserExample();
		userExample.createCriteria().andUsernameEqualTo(username);
		List<User> users = userMapper.selectByExample(userExample);
		SelfUserDetails userDetails = new SelfUserDetails();
		userDetails.setUsername(username);
		if (!users.isEmpty()) {
//			userDetails.setPassword(users.get(0).getPassword());
			// 使用BCryptPasswordEncoder 对密码进行加密
			userDetails.setPassword(new BCryptPasswordEncoder().encode(users.get(0).getPassword()));
		}
		return userDetails;
	}
}
